<template>
  <div class="layout-container">
    <div style="padding: 0 10px;">
      <h1>合同起草</h1>
      <!-- 合同信息表单 -->
      <el-card class="box-card">
      <el-form ref="contractForm" :model="contractForm" label-width="100px">
        <el-form-item label="合同名称">
          <el-input v-model="contractForm.name"></el-input>
        </el-form-item>
        <el-form-item label="合同编号">
          <el-input v-model="contractForm.number"></el-input>
        </el-form-item>
        <el-form-item label="客户">
          <!-- 下拉框组件，支持多选 -->
          <el-select v-if="customerOptions.length" v-model="contractForm.customers" multiple placeholder="请选择">
            <el-option
                    v-for="item in customerOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会签开始时间">
          <!-- 日历组件 -->
          <el-date-picker
                  v-model="contractForm.startDate"
                  type="date"
                  placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会签结束时间">
          <!-- 日历组件 -->
          <el-date-picker
                  v-model="contractForm.endDate"
                  type="date"
                  placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="上传附件">
          <!-- 文件上传组件 -->
          <el-upload
                  :action="sendUrl"
                  :headers="con_id"
                  :on-success="handleSuccess"
                  :on-error="handleError"
                  :accept="'.doc,.docx,.pdf'"
                  :on-exceed="handleExceed"
                  :before-upload="beforeUpload"
                  >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">可以上传 Word(.doc, .docx) 和 PDF(.pdf) 文件</div>
          </el-upload>
        </el-form-item>
        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存草稿</el-button>
        </el-form-item>
      </el-form>
      </el-card>
      <!-- 文本编辑器 -->
      <word-editor />
    </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref } from 'vue'
  import wordEditor from '@/views/main/components/wordEditor/index.vue'
  import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElDatePicker, ElUpload, ElButton } from 'element-plus'
  import axios from "axios";
  import {getUserNameApi} from "@/api/user";
  import {addNew} from "@/api/work";
  import {deleteNoName} from "@/api/work";
  import store from '@/store';

  export default defineComponent({
    components: {
      wordEditor,
      ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElDatePicker, ElUpload, ElButton
    },
    setup() {
      const contractForm = ref({
        name: '',
        number: '',
        customers: [],
        startDate: '',
        endDate: '',
        context: ''
      })
      const customerOptions = ref([]);
      const uploadUrl = 'localhost:8080/contract/addContract';
      const sendUrl = 'localhost:8080/File/upFile';
      let filePath = ''
      let con_id = ''
      const userid = localStorage.getItem('userId')
      addNew(String(userid)).then(data =>{
        con_id = data.data.con_id;
      })
      getUserNameApi().then(data =>{
        customerOptions.value = data.data.map((customer: { name: string; id: number }) => ({
          value: customer.id,
          label: customer.name
        }));
      })
      const fileUrls = ref([]) // 用于存储上传文件的 URLs
      const handleExceed = (files :any, fileList:any) => {
        // 文件数量超出限制时的处理
        console.log('文件数量超出限制', files, fileList);
      }

      const beforeUpload = (file:any) => {
        // 文件上传前的验证
        const isLt100M = file.size / 1024 / 1024 < 100;
        if (!isLt100M) {
          console.error('文件大小不能超过 100MB!');
        }
        return isLt100M;
      }

      const handleSuccess = (response:any, file:any, fileList:any) => {
        // 文件上传成功后的处理
        console.log('文件上传成功', response, file, fileList)
        filePath = file.url;
      }

      const handleError = (err:any, file:any, fileList:any) => {
        // 文件上传失败后的处理
        console.log('文件上传失败', err, file, fileList)
      }

      const beforeDestroy = () => {
        deleteNoName(String(userid)).then(data =>{})
      }

      const submitForm = async () => {
        // 构建请求体
        const formData = new FormData()
        // 假设 contractForm.value.customers 是一个包含字符串的数组
        let customersList = "";
        contractForm.value.customers.map(customer => customersList += customer + ",");
        formData.append('con_id',con_id)
        formData.append('name', contractForm.value.name)
        formData.append('number', contractForm.value.number)
        formData.append('customers', customersList)
        formData.append('startDate', contractForm.value.startDate)
        formData.append('endDate', contractForm.value.endDate)
        formData.append('context', contractForm.value.context)
        fileUrls.value.forEach((url:any, index:any) => {
          formData.append(`fileUrls[${index}]`, url)
        })

        try {
          const response = await axios.post(uploadUrl, formData)
          console.log('Form submitted successfully', response)
          // 清空表单和文件列表
          contractForm.value = {
            name: '',
            number: '',
            customers: [],
            startDate: '',
            endDate: '',
            context: ''
          }
          fileUrls.value = []
          console.log('合同提交成功')
        } catch (error) {
          console.error('Error submitting form', error)
          console.error('合同提交失败')
        }
      }

      return {
        con_id,
        sendUrl,
        contractForm,
        customerOptions,
        handleSuccess,
        handleError,
        beforeUpload,
        handleExceed,
        submitForm
      }
    }
  })
</script>

<style lang="scss" scoped>
  // 样式部分可以根据需要添加
</style>